local skynet = require 'skynet'
require 'skynet.manager'

skynet.error('lesson1 started')

function ToKey(x, y)
    return x * 10000 + y
end

function CollectMarchThroughGrids(gx1, gy1, gx2, gy2)
    local grids = {}
    if gx1 == gx2 then
        if gy1 > gy2 then
            gy1, gy2 = gy2, gy1
        end
        for y = gy1, gy2 do
            local key = ToKey(gx1, y)
            grids[key] = {
                x = gx1,
                y = y
            }
        end
    elseif gy1 == gy2 then
        if gx1 > gx2 then
            gx1, gx2 = gx2, gx1
        end
        for x = gx1, gx2 do
            local key = ToKey(x, gy1)
            grids[key] = {
                x = x,
                y = gy1
            }
        end
    else
        local k = (gy2 - gy1) / (gx2 - gx1)
        if gx1 > gx2 then
            gx1, gx2 = gx2, gx1
            gy1, gy2 = gy2, gy1
        end
        for x = gx1, gx2 do
            local y = math.floor(k * x)
            local key = ToKey(x, y)
            --skynet.error("key="..key..", x="..x..", y="..y)
            if grids[key] then
            else
                grids[key] = {
                    x = x,
                    y = y
                }
            end
        end
        if gy1 > gy2 then
            gy1, gy2 = gy2, gy1
            gx1, gx2 = gx2, gx1
        end
        for y = gy1, gy2 do
            local x = math.floor(y / k)
            local key = ToKey(x, y)
            --skynet.error("key="..key..", x="..x..", y="..y)
            if grids[key] then
            else
                grids[key] = {
                    x = x,
                    y = y
                }
            end
        end
    end
    return grids
end

skynet.start(
    function()
        skynet.timeout(
            300,
            function()
                skynet.error('lesson1 end')
                skynet.sleep(0)
                skynet.abort()
            end
        )

        local grids = CollectMarchThroughGrids(1, 2, 2, 20)
        for key, pos in pairs(grids) do
            skynet.error('grids[' .. key .. ']: x=' .. pos.x .. ' y=' .. pos.y)
        end
    end
)
